package com.ele.client.auth;

import com.ele.client.Presenter;
import com.ele.client.rpc.ApplicationServiceAsync;
import com.ele.client.rpc.SimpleAsyncCallback;
import com.ele.client.util.PathHelper;
import com.ele.model.AppUser;
import com.github.gwtbootstrap.client.ui.AlertBlock;
import com.github.gwtbootstrap.client.ui.Button;
import com.github.gwtbootstrap.client.ui.PasswordTextBox;
import com.github.gwtbootstrap.client.ui.TextBox;
import com.google.gwt.event.dom.client.*;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Widget;

public class LoginPresenter implements Presenter {

    public interface Display {
        Widget asWidget();

        TextBox getEmailTextBox();

        PasswordTextBox getPasswordTextBox();

        Button getSignInButton();

        AlertBlock getAlertBlock();
    }

    private final ApplicationServiceAsync rpcService;
    private final HandlerManager eventBus;
    private final Display display;

    public LoginPresenter(ApplicationServiceAsync rpcService, HandlerManager eventBus, Display display) {
        this.rpcService = rpcService;
        this.eventBus = eventBus;
        this.display = display;
    }

    public void go(final HasWidgets container) {
        bind();
        container.clear();
        container.add(display.asWidget());

        display.getEmailTextBox().setFocus(true);
    }

    private void bind() {
        display.getSignInButton().addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                login();
            }
        });

        KeyDownHandler keyDownHandler = new KeyDownHandler() {
            @Override
            public void onKeyDown(KeyDownEvent event) {
                if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
                    login();
                }
            }
        };

        display.getEmailTextBox().addKeyDownHandler(keyDownHandler);
        display.getPasswordTextBox().addKeyDownHandler(keyDownHandler);
    }

    private void login() {
        display.getSignInButton().state().loading();

        rpcService.login(display.getEmailTextBox().getValue(), display.getPasswordTextBox().getValue(), new SimpleAsyncCallback<AppUser>() {
            @Override
            public void onSuccess(AppUser user) {
                boolean successful = user != null;

                if (successful) {
                    PathHelper.setAction("home");
                    History.fireCurrentHistoryState();
                } else {
                    display.getAlertBlock().setVisible(true);
                    display.getSignInButton().state().reset();
                }
            }
        });
    }
}
